﻿@model QBWeb.ViewModels.QuestionViewModels

@Styles.Render("~/Content/add-style.css")
@{
    ViewBag.Title = "编辑试卷";
}
<style>
    .div-order {
        border: 1px solid;
        border-color: blue;
        float: left;
        width: 100px;
        height: 50px;
        margin: 10px;
    }
    .keys{
        color:red
    }
</style>
<link rel="stylesheet" href="~/Scripts/drag/style.css" type="text/css" media="screen" />
<script type="text/javascript" src="~/Scripts/drag/drag.js"></script>
<div class="row" style="background-color: #FAFAFA !important;">
    <div class="col-sm-3">
        <div class="panel panel-default" style="margin-top:20px;padding:6px;text-align:center;">
            <h3>共<b id="sum-questions"></b>题</h3>
            <div>
                选择题：共 <b id="sum-singleChoice"></b> 题
            </div>
            <div>
                填空题：共 <b id="sum-blank"></b> 题
            </div>
            <div>
                判断题：共 <b id="sum-judge"></b> 题
            </div>
        </div>

        <div class="panel panel-default" style="margin-top:20px;padding:6px;text-align:center;">
            <h3>题型</h3>
            <input type="button" value="选择题" id="data-question-single" class="btn btn-info" />
            <input type="button" value="填空题" id="data-question-blank" class="btn btn-info" />
            <input type="button" value="判断题" id="data-question-trueFalse" class="btn btn-info" />

            <div style="text-align:center;margin-top:20px;">
                <button class="layui-btn layui-btn-lg" type="button" id="SaveQuestions" onclick="Save()">保存</button>
            </div>
        </div>

    </div>

    <div id="div1" class="col-sm-9 ">
        <div class="panel panel-default" style="margin-top:20px;padding:6px;">
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="setScore">
                批量给分
            </button>
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="openView" onclick="btnShow()">
                word导入
            </button>
            @* <a href="~/WordImport/Index" class="layui-btn layui-btn-radius layui-btn-normal">word导入</a>*@

            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="setVolume">
                手动组卷
            </button>
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="smartSetVolume">
                智能组卷
            </button>
            @*<button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="setLevel">
                    设置难度
                </button>*@
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="setOrder">
                调整顺序
            </button>
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="setSaveDB">
                一键确定
            </button>
        </div>

        <p id="add">添加试题</p>
    </div>
</div>


<script src="~/Scripts/indexedDB.js"></script>
<script src="~/Scripts/add-question.js"></script>
<script src="~/Scripts/insertQuest.js"></script>

<script>
    $(document).ready(function() {
        deleteDB("questions"); //删掉数据库
    });
    
    var testPaperId = @Model.TestPaperTb.Id;
    var allQuestions;

    getQuestionJson(testPaperId, null);

    //保存题目
    function Save() {
        var tools = $('.tools');
        for (let i = 0; i < tools.length; i++) {
            if ($(tools[i]).attr('data-hide') == '0') {
                layer.msg("第" + (i + 1) + "题没有点击确定，请点击确定后重试");
                return false;
            }
        }
        readAll();
    }
    //删除所选题目
    $("div").on("click",
        "#remove-div",
        function () {
            var e = $(this).attr("data-Index");
            var formData = $("#data-Index-" + e);
            var questId = formData.find(".Index").attr("data-Question-Id");
            read(e, null, 'remove');
            //通过被选择的元素，向上查找两个父节点，后删除父节点
            $(this).parent().parent().remove();
            layer.msg("删除成功");
            $.ajax({
                //async: false,
                url: '/Main/RemoveQuestion',
                type: 'post',
                dataType: 'text',
                data: {
                    id: testPaperId,
                    questId: questId
                },
                success: function(json) {
                    //layer.msg(json);
                }
            });
        });

    //给页面的题目添加一个唯一不变的id
    //var y = 0;
    //function OS() {
    //    var quest = $(".Index");
    //    for (var x = 0; x < quest.length; x++) {
    //        if ($(quest[y]).attr("data-Index") === undefined) {
    //            $(quest[y]).attr("data-Index", y);
    //            y++;
    //        }
    //    }
    //}

</script>
<script>
    var knowledges,knowledge;
    var know = [];//已选知识点

    //选项卡 依赖 element 模块，否则无法进行功能性操作
    layui.use(['element', 'layer'],
        function () {
            element = layui.element, layer = layui.layer;

            element.on('tab(docTab)',
                function (ele) {
                    var a = ele.index;
                    console.log(ele);
                    activeAjax(a);
                });
        });

    function activeAjax(index) {
        $.ajax({
            type: "POST",
            url: "/Main/ResultCard",
            data: { CardIndex: index },
            dataType: "HTML",
            success: function (data) {
                $(".layui-tab-content").empty();
                $(".layui-tab-content").append(data);
            }
        });
    }

    $("#setVolume").click(function () {
        OpenSetVolume();
    });
    //手动组卷
    function OpenSetVolume() {
        layui.use('layer', function () {
            layer.open({
                type: 1
                , title: false
                , closeBtn: false
                , area: ['80%', '90%']
                , shade: 0.8
                , id: 'timedown' //设定一个id，防止重复弹出
                , btn: ['确定', '返回']
                , content: ' <div class="row" style="width:95%;padding: 10px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;style="background-color: #FAFAFA !important;">'

                    + '<div class= "layui-tab layui-tab-brief" lay-filter="docTab" >'
                    + '<ul class="layui-tab-title">'
                    + '<li class="layui-this">固定试题组卷</li>'
                    + '<li>随机抽题组卷</li>'
                    + '</ul>'

                    + '<div class="layui-tab-content layui-show">'
                    + '<div id="test1"></div>'
                    + '</div>'

                    + '</div>'
                    + '</div>'
                , btn1: function (index, layero) {
                    if (quest.length != 0) {
                        var dd = quest.join(";");
                        getQuestionJson(testPaperId, dd);
                        layer.close(index);
                    }
                    else {

                        var dd = know.join(";");
                        if (totle()) {
                            knowid(testPaperId, dd);
                            layer.close(index);
                        }
                        
                    }

                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
            activeAjax(0);
        });
    }


    // a：总题目  b:判断题  c:选择题  d：填空题
    var a = 20; b = 5, c = 10, d = 5;
    function totle() {
        //判断
        if (document.getElementById('Judge').value != "") {
            if (isNaN(document.getElementById('Judge').value)) {
                layer.msg("输入判断题的题数需为数字");
                return false;
            }
            b = document.getElementById('Judge').value;
        }
        //选择
        if (document.getElementById('Choose').value != "") {
            if (isNaN(document.getElementById('Choose').value)) {
                layer.msg("输入选择题的题数需为数字");
                return false;
            }
            c = document.getElementById('Choose').value;
        }
        //填空
        if (document.getElementById('FillInBlanks').value != "") {
            if (isNaN(document.getElementById('FillInBlanks').value)) {
                layer.msg("输入填空题的题数需为数字");
                return false;
            }
            d = document.getElementById('FillInBlanks').value;
        }
        //总题目
        if (document.getElementById('Judge').value != "" || document.getElementById('Choose').value != "" || document.getElementById('FillInBlanks').value != "") {
            a = Number(document.getElementById('Judge').value) + Number(document.getElementById('Choose').value) + Number(document.getElementById('FillInBlanks').value);
        }
        //x = document.getElementById('difficulty').value;
        return true;
    }
    $("#smartSetVolume").click(function () {
        OpenSmartVolume();
    })
    function OpenSmartVolume() {
        layui.use('layer', function () {
            layer.open({
                type: 1
                , title: "智能组卷"
                , closeBtn: false
                , area: ['80%', '90%']
                , shade: 0.6
                , id: 'LAY_score'
                , btn: ['确定', '取消']
                , content: `<div class="col-md-3">
                                <div class="panel panel-default" style="height:200px;">
                                    <h5 style="text-align:center">判断题： <input type="text" class="form-control" style="width:50px;display:inline;height:30px;" id="Judge" /> 题</h5>
                                    <h5 style="text-align:center">选择题： <input type="text" class="form-control" style="width:50px;display:inline;height:30px;" id="Choose" /> 题</h5>
                                    <h5 style="text-align:center">填空题： <input type="text" class="form-control" style="width:50px;display:inline;height:30px;" id="FillInBlanks" /> 题</h5>
                                     <br />
                                     <br />
                                    <div class="panel panel-default" style="height:200px;">
                                        <form action="/Main/Choose">
                                            <h5 style="text-align:center">小知识点选了<b id="ChooseFewQuestions">0</b>个</h5>
                                            <div style="margin:10px;">
                                                <h5 style="display:inline;">知识点：</h5>
                                                <select class="form-control" id="BigKnowledge" style="display:inline;width:60%">
                                                    <option value="未分类">未分类</option>
                                                </select>
                                            </div>
                                            <div style="text-align:center;padding-top:20px;">
                                                <input type="button" class="layui-btn" value="全部小知识点" id="showAllSmallKnow" />
                                                <input type="button" class="layui-btn" value="查询" id="selectKnow" />
                                            </div>
                                        </form>
                                    </div>
                                </div>
                             </div>
                                <div class="col-md-9">
                                    <div class="panel panel-default" style="height:auto;">
                                        <div class="row" id="title">
                                            <div class="col-md-2 col-sm-2">

                                            </div>
                                            <div class="col-md-5 col-sm-5">大知识点</div>
                                            <div class="col-md-5 col-sm-5">小知识点</div>

                                            <hr />
                                        </div>
                                        <div id="table_body">

                                        </div>
                                    </div>

                                    <div id="demo1"></div>
                                </div>`
                , btn1: function (index, layero) {
                    totle();
                    var arr = [],points=[1,2];
                    arr.push(c)
                    arr.push(b);
                    arr.push(d)
                    arr.push(0);
                    arr.push(0);
                    getSmartVolume(arr, points);
                    layer.close(index);
                }, btn2: function (index, layero) {
                    layer.close(index);
                }
                
            });
            getKnowledge();
            getKnow();
        });
    }
    function getSmartVolume(questSum,points) {
        //var questSum = [1, 0, 10, 0, 0];
        var scoreSum = [2, 2, 2, 2, 2];
        //var points = [1, 2];
        $.ajax({
            url: '/GA/show',
            type: 'post',
            dataType: 'json',
            data: {
                questSum: questSum,
                scoreSum: scoreSum,
                points: points
            },
            timeout: 10000,
            success: function (json) {
                if (json.success) {
                    ShowQuestion(false, json.data);
                    allQuestions = json.data;
                } else {
                    console.log(json);
                }
            }
        })
    }

    //获取所有知识点的数据
    function getKnowledge() {
        $.ajax({
            async: 'async',
            url: '/Main/GetKnowledge',
            type: 'get',
            dataType: 'json',
            timeout: 5000,
            success: function (json) {
                knowledges = json;
                showKnowledge(knowledges, "BigKnowledge");
            }
        });
    };

    //获取知识点
    function getKnow() {
        $.ajax({
            async: false,
            url: '/Main/ResualAllKnow',
            type: 'get',
            dataType: 'json',
            timeout: 5000,
            success: function (json) {
                knowledge = json;
                layOpen(knowledge);
            },
        });
    };

    //查询知识点
    $("#selectKnow").click(function () {
        var item = $("#BigKnowledge").find("option:selected").val();
        var knows = [];
        for (var i in knowledge) {
            if (item == knowledge[i].KnowID) {
                knows.push(knowledge[i].BigKnowID);
            }
        }
        if (knows.length == 0) {
            layer.msg("该知识点内无题目");
        } else {
            $("#table_body").html("");
            var newArr = isExistArr(knowledge, knows);
            layOpen(newArr);
        }
    });

    //显示所有知识点
    $("#showAllSmallKnow").click(function () {
        $("#table_body").html("");
        layOpen(knowledge);
    });


    function layOpen(data) {
        layui.use(['laypage', 'layer'], function () {
            var laypage = layui.laypage, layer = layui.layer;
            laypage.render({
                elem: 'demo1'
                , count: data.length
                , jump: function (obj) {
                    document.getElementById('table_body').innerHTML = function () {
                        var arr = [], thisData = data.concat().splice(obj.curr * obj.limit - obj.limit, obj.limit);
                        layui.each(thisData, function (index, item) {
                            var items = '<div class="row">'
                                + '<div class="col-md-2 col-sm-2" style="text-align:center;">'
                                + '<input type="checkbox" onclick="IsChecked(this)" value="' + thisData[index].KnowID + '" />'
                                + '</div >'
                                + '<div class="col-md-5 col-sm-5">' + thisData[index].BigKnowName + '</div>'
                                + '<div class="col-md-5 col-sm-5">' + thisData[index].SmallKnowName + '</div>'
                                + '</div><hr style="margin: 10px 0;"/>';
                            arr.push(items);
                        });
                        return arr.join('');
                    }();
                }
            });
        });
    }

    //显示知识点
    function showKnowledge(data, knowledge) {
        $("#" + knowledge).empty();
        $.each(data, function (i, item) {
            $("<option></option>")
                .val(data[i].Value)
                .text(data[i].Text)
                .appendTo($("#" + knowledge))
        });
    }

    function isExistArr(arr1, arr2) {   // arr1原数组   arr2 要查找的数组 
        var new_arr = [];
        arr1.forEach(function (item, idx) {
            if (arr2.indexOf(item.BigKnowID) != -1) {
                new_arr.push(item);
            }
        })
        return new_arr;
    }

    function IsChecked(obj) {
        Checke = $(obj).prop('checked');
        var arr = [], x = 0;
        if (Checke == true) {
            know.push($(obj).val());
        } else {
            var item = know.indexOf($(obj).val());
            delete know[item];
            for (var i in know) {
                if (know[i] == undefined) continue;
                arr[x++] = know[i];
            }
            know = arr;
        }

        document.getElementById('ChooseFewQuestions').innerHTML = know.length;
    };
</script>




<div class="modal fade" id="firstModal" data-backdrop="static">
    <div class="modal-dialog modal-lg" style="width: 90%;">
        <div class="modal-content">

            <!-- 模态框头部 -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true" style="font-size:30px">×</span></button>

                <button class="modal-title btn btn-primary" type="button" onclick="btnWakeFile()">导入Word文档</button>

            </div>

            <!-- 模态框主体 -->
            <div class="modal-body" id="questions">

                <div class="layui-row" style="">
                    <div class="layui-col-md6" style="border-right: solid 1px lightgray;">
                        <div id="leftRef" style="height: 540px;">
                            <textarea class="layui-textarea textareaClass" name="textData" form="WordForm2"></textarea>
                        </div>
                    </div>
                    <div class="layui-col-md6" style=" height: 540px; overflow:auto; word-wrap: break-word;padding-left:5px" id="rightRef">
                        <!-- 要更新的内容 Ref=Refresh-->

                    </div>
                </div>

            </div>

            <!-- 模态框底部 -->
            <div class="modal-footer " style="text-align: center">
                <button type="button" class="btn btn-success" onclick="btnSubmit(NA2)">识别</button>
                @*<button type="button" class="btn btn-primary" onclick="btnSubmit(NA3)">确定导入</button>*@
                <button type="button" class="btn btn-primary" id="btn2" onclick="WriteDown()">确定导入</button>
                <button type="button" class="btn btn-default" data-dismiss="modal" aria-label="Close">取消</button>
            </div>

        </div>
    </div>
</div>



@using (Ajax.BeginForm("Upload", "WordImport", null,
    new AjaxOptions()
    {
        HttpMethod = "Post",
        InsertionMode = InsertionMode.Replace,
        Confirm = "确定导入？",
        UpdateTargetId = "leftRef",
        OnBegin = "oS()",
        OnSuccess = "oE()"
    },
    new { @enctype = "multipart/form-data", id = "WordForm" }))
{
    <input type="file" style="display:none" name="wordFile" class="btn-default" id="fileWord" onchange="btnSubmit(NA)" form="WordForm" />
    <input type="submit" id="NA" style="display:none " />
}
@using (Ajax.BeginForm("Recognition", "WordImport", null,
    new AjaxOptions()
    {
        HttpMethod = "Post",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "rightRef",
        OnBegin = "oS()",
        OnSuccess = "oE2()"
    },
    new { id = "WordForm2" }))
{
    <input type="submit" id="NA2" style="display:none " />
}

<script>
    function btnSubmit(id) {

        $(eval(id)).click();  //小bug，不能直接触发ajax表单，只能这样
    }
    function btnShow() {
        //$("#btn2").attr("href", "javascript:void(0);");
        $('#firstModal').modal('show');
    }
    function btnWakeFile() {
        $('#fileWord').click();
    }

    function btnHide() {
        $('#firstModal').modal('hide');
    }

    function oS() {

        layer.msg('请稍等..', {
            icon: 16
            , shade: 0.3
            , time: 10000
        });
    }

    function oE() {
        layer.closeAll();
    }
    function oE2() {
        layer.closeAll();
        //$("#btn2").attr("href", "/WordImport/ResultToView");
        //$("#btn2").attr("onclick", "oS()");
    }
    function WriteDown() {
        $.ajax({
            url: '/WordImport/ResultToView',  // 跨域URL
            type: 'post',
            dataType: 'json',
            /* timeout: 5000,*/
            success: function (json) {
                if (json.length != undefined) {
                    ShowQuestion(false,json);
                }
            }
        });
        layer.closeAll();
        btnHide();
    }
</script>